package boot.spring.controller;

import boot.spring.mapper.LabApplyMapper;
import boot.spring.pagemodel.HistoryProcess;
import boot.spring.pagemodel.RunningProcess;
import boot.spring.po.Lab;
import boot.spring.service.LabService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricProcessInstanceQuery;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.runtime.ProcessInstanceQuery;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(value = "请假流程接口")
@Controller
public class LabController {
	@Autowired
	RepositoryService rep;
	@Autowired
	RuntimeService runservice;
	@Autowired
	FormService formservice;
	@Autowired
	IdentityService identityservice;
	@Autowired
	LabService labService;
	@Autowired
	TaskService taskservice;
	@Autowired
	HistoryService histiryservice;

	@Autowired
	LabApplyMapper labApplyMapper;

	@RequestMapping(value = "/lab/uploadworkflow", method = RequestMethod.GET)
	@ResponseBody
	public String fileupload() {
		//1，创建processEngine对象
		ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
		//2，得到repositoryService实例
		RepositoryService repositoryService = processEngine.getRepositoryService();
		//3，进行部署
		Deployment deployment = repositoryService.createDeployment()
				.addClasspathResource("process/lab_apply.bpmn") //添加bpmn资源
				.addClasspathResource("process/lab_apply.png")
				.name("实验申请流程")
				.deploy();

		//4，输出部署的一些信息
		System.out.println(deployment.getId());
		System.out.println(deployment.getName());

		return "部署成功";
	}


	@RequestMapping(value = "/lab/deletedeploy", method = RequestMethod.GET)
	@ResponseBody
	public String deletedeploy(@RequestParam("deployid") String deployid) throws Exception {
		rep.deleteDeployment(deployid, true);
		return "部署的流程删除成功";
	}


//开始流程
	@RequestMapping(value = "/lab/startlab", method = RequestMethod.GET)
	@ResponseBody
	public String start_lab(@RequestParam(value = "userid") String userid) {
		Lab apply = new Lab();
		apply.setId(2);
		apply.setNumber("31".toString());
		Map<String, Object> variables = new HashMap<String, Object>();
		variables.put("applyuserid", userid);
		ProcessInstance ins = labService.startWorkflow(apply, userid, variables);
		System.out.println("流程id" + ins.getId() + "已启动");
		return "启动成功sucess";
	}

	@ApiOperation("获取领导审批代办列表")
	@RequestMapping(value = "/lab/depttasklist",method = RequestMethod.GET)
	@ResponseBody
	public List<Lab> getdepttasklist(@RequestParam(value = "userid")String userid) {
		List<Lab> results = labService.getalldepttask(userid);
		System.out.println(results.toString());
		System.out.println("获取管理成功");
		return  results;
	}
//得到调整申请的列表
	@RequestMapping(value = "/lab/getupdatatasklist", method = RequestMethod.GET)
	@ResponseBody
	public List<Lab> getupdatatasklist(@RequestParam(value = "userid") String userid) {
		List<Lab> results = labService.getupdateapplytask(userid);
		return results;
	}

//得到你要处理任务的申请
	@RequestMapping(value = "/lab/getdealtask", method = RequestMethod.GET)
	@ResponseBody
	public Lab gettaskdeal(@RequestParam("taskid") String taskid) {
		Task task = taskservice.createTaskQuery().taskId(taskid).singleResult();
		ProcessInstance process = runservice.createProcessInstanceQuery().processInstanceId(task.getProcessInstanceId())
				.singleResult();
		Lab apply = labService.getlab(new Integer(process.getBusinessKey()));
		return apply;
	}

//领导审批
	@RequestMapping(value = "/lab/deptcomplete", method = RequestMethod.GET)
	@ResponseBody
	public String deptcomplete(@RequestParam("userid") String userid, @RequestParam("taskid") String taskid,@RequestParam("approve") String approve) {
		Map<String, Object> variables = new HashMap<String, Object>();
		variables.put("applyapprove", approve);
//		只能声明给同一个用户（可多次），不能再次声明，和setAssignee方法类似  任务声明(签收)
		taskservice.claim(taskid,userid);
		taskservice.complete(taskid,variables);
		return "领导审批成功";
	}

//调整申请的流程
	@RequestMapping(value = "/lab/updatecomplete/{taskid}", method = RequestMethod.POST)
	@ResponseBody
	public String updatecomplete(@PathVariable("taskid") String taskid, @ModelAttribute("lab") Lab lab,
			@RequestParam("reapply") String reapply) {
		labService.updatecomplete(taskid, lab, reapply);
		return "调整申请成功";
	}

 // 获得参与的正在运行的申请流程
	@RequestMapping(value = "/lab/involvedprocess", method = RequestMethod.GET)
	@ResponseBody
	public List<RunningProcess> allexeution(@RequestParam("userid") String userid){
		ProcessInstanceQuery query = runservice.createProcessInstanceQuery();
		List<ProcessInstance> a = query.processDefinitionKey("lab_apply").involvedUser(userid).list();
		List<RunningProcess> list = new ArrayList<RunningProcess>();
		for (ProcessInstance p : a) {
			RunningProcess process = new RunningProcess();
			process.setActivityid(p.getActivityId());
			process.setBusinesskey(p.getBusinessKey());
			process.setExecutionid(p.getId());
			process.setProcessInstanceid(p.getProcessInstanceId());
			list.add(process);
		}
		return list;
	}

// 获得完成的申请历史流程实例
	@RequestMapping(value = "/lab/getfinishprocess", method = RequestMethod.GET)
	@ResponseBody
	public List<HistoryProcess> getHistory(@RequestParam("userid") String userid) {
		HistoricProcessInstanceQuery process = histiryservice.createHistoricProcessInstanceQuery()
				.processDefinitionKey("lab_apply").startedBy(userid).finished();
		List<HistoricProcessInstance> info = process.list();
		List<HistoryProcess> list = new ArrayList<HistoryProcess>();
		for (HistoricProcessInstance history : info) {
			HistoryProcess his = new HistoryProcess();
			String bussinesskey = history.getBusinessKey();
			Lab lab = labService.getlab(Integer.parseInt(bussinesskey));
			his.setLab(lab);
			his.setBusinessKey(bussinesskey);
			his.setProcessDefinitionId(history.getProcessDefinitionId());
			list.add(his);
		}
		return list;
	}

//	历史活动查看(某一次流程的执行经历的多少步)
	@RequestMapping(value = "/lab/processinfo", method = RequestMethod.GET)
	@ResponseBody
	public List<HistoricActivityInstance> processinfo(@RequestParam("instanceid") String instanceid) {
		List<HistoricActivityInstance> his = histiryservice.createHistoricActivityInstanceQuery()
				.processInstanceId(instanceid).orderByHistoricActivityInstanceStartTime().asc().list();
		return his;
	}

//选择具有给定id的用户所涉及的历史进程实例。
	@RequestMapping(value = "/lab/setupprocess", method = RequestMethod.GET)
	@ResponseBody
	public List<RunningProcess> setupprocess(@RequestParam("userid") String userid) {
		ProcessInstanceQuery query = runservice.createProcessInstanceQuery();
		int total = (int) query.count();
		List<ProcessInstance> a = query.processDefinitionKey("lab_apply").involvedUser(userid).list();
		List<RunningProcess> list = new ArrayList<RunningProcess>();
		for (ProcessInstance p : a) {
			RunningProcess process = new RunningProcess();
			process.setActivityid(p.getActivityId());
			process.setBusinesskey(p.getBusinessKey());
			process.setExecutionid(p.getId());
			process.setProcessInstanceid(p.getProcessInstanceId());
			Lab l = labService.getlab(Integer.parseInt(p.getBusinessKey()));
			if (l.getUser_id().equals(userid))
				list.add(process);
			else
				continue;
		}

		return list;
	}

}
